package cn.js.sangu.unitStore.service.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.js.sangu.unitStore.common.MyLogsAOP;
import cn.js.sangu.unitStore.entity.Logs;
import cn.js.sangu.unitStore.entity.User;
import cn.js.sangu.unitStore.service.LogsService;
import cn.js.sangu.unitStore.service.UserService;
import cn.js.sangu.unitStore.utils.IpUtil;
import cn.js.sangu.unitStore.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;

@Component
@Aspect //标记为切面
@Slf4j
public class LogsAspect {

    @Resource
    LogsService logsService;

    @Resource
    UserService userService;

    @AfterReturning(pointcut = "@annotation(logsAOP)",returning = "jsonRes")
    public void recordLog(JoinPoint point, MyLogsAOP logsAOP,Object jsonRes){
        //当前登录的用户，捕捉不到导出请求的用户
        User user = TokenUtils.getCurrentUser();
        //未登录就是Null,要从参数获取操作人员信息（没有登录的请求，如注册请求）
        if (null == user) {
            Object[] args = point.getArgs();
            if (ArrayUtil.isNotEmpty(args)) {
                //参数非空，取出并强转给用户对象
                if (args[0] instanceof User) {
                    user = (User) args[0];
                }
            }
        }
        //获取IP
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        String none = "未获取到";
        String ipAddr = none;
        Integer uid = 0;
        String username = none;
        if (null!=attributes){
//            ipAddr = IpUtil.getIpAddr(attributes.getRequest());
            ipAddr = IpUtil.getClientIp(attributes.getRequest());
        }

        if (null!=user){
            if (StrUtil.isNotBlank(user.getName())){
                uid = user.getId();
                username = user.getName();
            }else {
                //注意：登录时没有token，所以也没有用户昵称空的需要根据账号从数据库查出用户昵称
                if(StrUtil.isNotBlank(user.getUsername())){
                    User userDB = userService.findByUserName(user.getUsername());
                    username = userDB.getName();
                    uid = userDB.getId();
                }
            }
        }else {
            log.error("记录日志异常：未获取到当前User对象");
        }

        Logs logs = Logs.builder()
                .uid(uid)
                .username(username)
                .operation(logsAOP.operation())
                .operaType(logsAOP.operaType().getValue())
                .operaIp(ipAddr)
                .operaTime(DateUtil.date())
                .remark(ipAddr.contains("192.168.111")?"内网":"互联网")
                .build();

        //多线程异步插入数据库,防止插入慢而影响其他功能
        ThreadUtil.execAsync(()->{
            logsService.save(logs);
        });

    }


}
